package com.tianpengtech.front.mobile.common.util;


import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.tianpengtech.common.model.user.User;

/**
 * Created by Administrator on 2017/7/18 0018.
 */
public class UserUtil {

    private static final String CACHE_NAME = "mobile_user";

    /**
     * 获取当前登录用户
     * @return
     */
    public static User getCurrentUser(String token, String source) {
//    	token="4304585384ecef7061eb176ffed77f9c";
        User user = CacheKit.get(CACHE_NAME,source.toUpperCase()+"_USER_CLIENT_" + token);
        if (user != null) {
            setCurrentUser( user, token, source);
        }else{
        	Record record = queryUserByToken(token);
            return User.dao.findById(record.getInt("user"));
        }
    	user.set(User.ID, user.get(User.ID));
        return user;

    }

    /**
     * 设置当前登录用户到cookie
     * @param user
     * 描述：加密串分两层，外层使用系统公共密钥加密，内层使用用户私有密钥加密
     */
    public static void setCurrentUser(User user,String token,String source) {
        /**
         * token
         * 方式登陆
         * */
        //获取配置文件中的超时时间，并转换为秒
        CacheKit.put(CACHE_NAME,source.toUpperCase()+"_USER_CLIENT_"+token,user);
    }

    
    private static Record queryUserByToken(String token){
    	String sql="select * from fair_token where token=?";
    	Record record= Db.findFirst(sql,token);
    	return record;
    }
    
    public static void updateUserToken(String token,long user){
    	Record record= queryUserByToken(token);
    	if(record==null){
    		Record temp = new Record();
    		temp.set("token", token);
    		temp.set("user", user);
    		Db.save("fair_token", temp);
    	}else{
    		record.set("token", token);
    		record.set("user", user);
    		Db.update("fair_token", record);
    	}
    }
    
    
    /**
     * 从缓存中删除token
     */
    public static void removeUser(String token){
        CacheKit.remove(CACHE_NAME,"USER_CLIENT_"+token);
    }
}
